package com.starsea.book.ui.newpage.activity

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.lxj.xpopup.XPopup
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.ActivityLotteryTiggerBinding
import com.starsea.book.ui.newpage.LoginActivity
import com.starsea.book.ui.newpage.adapter.LotteryRecordAdapter
import com.starsea.book.ui.newpage.adapter.LotteryTiggerMonthPrizeAdapter
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.LotteryInfoEntity
import com.starsea.book.ui.newpage.pop.LotteryTiggerPrizePop
import com.starsea.book.ui.newpage.utils.finialDouble
import com.starsea.book.ui.newpage.viewmodel.WelfareViewModel
import com.starsea.book.ui.newpage.weidget.welfaregame.wv.AbstractWheelAdapter
import com.starsea.book.ui.newpage.weidget.welfaregame.wv.OnWheelScrollListener
import com.starsea.book.ui.newpage.weidget.welfaregame.wv.WheelView
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding
import kotlin.random.Random


/**
 * @author Lee
 * @createTime 2024-02-22 14 GMT+8
 * @desc : 老虎机抽奖
 */
class LotteryTiggerActivity : VMBaseActivity<ActivityLotteryTiggerBinding, WelfareViewModel>() {

    override val binding by viewBinding(ActivityLotteryTiggerBinding::inflate)
    override val viewModel by viewModels<WelfareViewModel>()

    var times = 3000

    var allCount = 0

    lateinit var mAdapter: LotteryRecordAdapter
    lateinit var mPrizeAdapter: LotteryTiggerMonthPrizeAdapter
    var listLottery: List<LotteryInfoEntity> = arrayListOf()
    var result: BaseEntity<MutableList<LotteryInfoEntity>>? = null


    override fun onActivityCreated(savedInstanceState: Bundle?) {


        mAdapter = LotteryRecordAdapter(this, 1) {

        }

        mPrizeAdapter = LotteryTiggerMonthPrizeAdapter(this, 1) {

        }

        binding.rvRecord.layoutManager = LinearLayoutManager(this)
        binding.rvRecord.adapter = mAdapter

        binding.rvThisMonthPrize.layoutManager = GridLayoutManager(this, 4)
        binding.rvThisMonthPrize.adapter = mPrizeAdapter


        binding.wlTiggerOne.viewAdapter = SlotMachineAdapter(this)
        binding.wlTiggerOne.visibleItems = 1
        binding.wlTiggerOne.isCyclic = true
        binding.wlTiggerOne.isEnabled = false
        binding.wlTiggerOne.setDrawShadows(true)
        binding.wlTiggerOne.setWheelBackground(R.drawable.shape_lottery_tigger_bg)


        binding.wlTiggerTwo.viewAdapter = SlotMachineAdapter(this)
        binding.wlTiggerTwo.visibleItems = 1
        binding.wlTiggerTwo.isCyclic = true
        binding.wlTiggerTwo.isEnabled = false
        binding.wlTiggerTwo.setDrawShadows(true)
        binding.wlTiggerTwo.setWheelBackground(R.drawable.shape_lottery_tigger_bg)


        binding.wlTiggerThree.viewAdapter = SlotMachineAdapter(this)
        binding.wlTiggerThree.visibleItems = 1
        binding.wlTiggerThree.isCyclic = true
        binding.wlTiggerThree.isEnabled = false
        binding.wlTiggerThree.setDrawShadows(true)
        binding.wlTiggerThree.setWheelBackground(R.drawable.shape_lottery_tigger_bg)


        binding.wlTiggerOne.addScrollingListener(object : OnWheelScrollListener {
            override fun onScrollingStarted(wheel: WheelView?) {

            }

            override fun onScrollingFinished(wheel: WheelView?) {
                val currentItem = binding.wlTiggerOne.currentItem
                LogUtils.e(">>>> currentItem = $currentItem")
            }

        })
        binding.wlTiggerTwo.addScrollingListener(object : OnWheelScrollListener {
            override fun onScrollingStarted(wheel: WheelView?) {

            }

            override fun onScrollingFinished(wheel: WheelView?) {
                val currentItem = binding.wlTiggerTwo.currentItem
                LogUtils.e(">>>> currentItem = $currentItem")
            }

        })
        binding.wlTiggerThree.addScrollingListener(object : OnWheelScrollListener {
            override fun onScrollingStarted(wheel: WheelView?) {

            }

            override fun onScrollingFinished(wheel: WheelView?) {
                val currentItem = binding.wlTiggerThree.currentItem
                LogUtils.e(">>>> currentItem = $currentItem")


                if (result != null) {
                    var coin = 0.0
                    var cash = 0.0
                    result!!.data!!.forEach {
//                    1、金币 2、会员
                        if (it.amountType == 1) {
                            coin += (it.amount ?: "0").toDouble()
                        } else {
                            cash += (it.amount ?: "0").toDouble()
                        }
                    }

                    XPopup.Builder(this@LotteryTiggerActivity)
                        .asCustom(LotteryTiggerPrizePop(this@LotteryTiggerActivity, coin, cash))
                        .show()


                    viewModel.lotteryNumberCheck(2, true)
                }


            }

        })


//        binding.rtvStart.setOnClickListener {
//
//            val num = Random.nextInt(9)
//            binding.wlTiggerOne.setCurrentItem(1)
//            binding.wlTiggerTwo.setCurrentItem(1)
//            binding.wlTiggerThree.setCurrentItem(1)
//
//            LogUtils.e(">>> randm = $num")
//            binding.wlTiggerOne.scroll(89 + num, times - 1000)
//            binding.wlTiggerTwo.scroll(89 + num, times)
//            binding.wlTiggerThree.scroll(89 + num, times + 1000)
//
//        }

        binding.rtvStart.setOnClickListener {
            viewModel.lotteryNumberCheck(2, false)
        }


        viewModel.lotteryList(2)
        viewModel.lotteryRedordReward(2)
        viewModel.lotteryNumberCheck(2, true)

        viewModel.lotteryNumberCheckResult.observe(this) {
            if (it.status == 200) {

                binding.rtvNumber.text = "今日剩余抽奖次数：${it.data!!.allCount}"

                allCount = it.data!!.allCount ?: 0

                if (!it.data!!.isCheck) {
                    if ((it.data!!.allCount ?: 0) > 0) {
                        ////下次抽奖是否要看视频 (0:否; 1:是)
                        if (it.data!!.nextIsAdvert == 1) {
                            val builder: AlertDialog.Builder =
                                AlertDialog.Builder(this)
                            builder.setTitle("温馨提示")
                            builder.setMessage("是否观看视频抽奖？")
                            builder.setPositiveButton("确定",
                                DialogInterface.OnClickListener { dialog, which -> //模拟位置
//                                    val position: Int = Random.nextInt(6) + 1
//                                    binding.lotteryView.startRotate(position)
                                    //看视频广告
//                                    viewModel.adverReward("", 5)

                                    showAdaVideo(5)
                                })
                            builder.setNegativeButton(
                                "取消"
                            ) { dialog, which ->

                            }
                            builder.show()
                        } else {
                            viewModel.lotteryTigger()
                            binding.rtvNumber.text =
                                "今日剩余抽奖次数：${(it.data!!.allCount ?: 0) - 1}"
                        }
                    } else {
                        toastOnUi("今日抽奖次数已用完")
                    }
                }

            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }


        viewModel.advertResult.observe(this) { data ->
            if (data.status == 200) {
                viewModel.lotteryTigger()
                binding.rtvNumber.text =
                    "今日剩余抽奖次数：${allCount - 1}"
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.lotteryRecordResult.observe(this) { data ->
            if (data.status == 200) {
                mAdapter.setItems(data.data!!)
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }


        viewModel.lotteryTiggerResult.observe(this) { data ->
            if (data.status == 200) {

                val num = Random.nextInt(9)
                binding.wlTiggerOne.currentItem = 1
                binding.wlTiggerTwo.currentItem = 1
                binding.wlTiggerThree.currentItem = 1

                LogUtils.e(">>> randm = $num")
                binding.wlTiggerOne.scroll(89 + num, times - 1000)
                binding.wlTiggerTwo.scroll(89 + num, times)
                binding.wlTiggerThree.scroll(89 + num, times + 1000)

                result = data


            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }



        viewModel.lotteryResult.observe(this) {
            if (it.status == 200) {

                it.data!!.forEachIndexed { index, lotteryInfoEntity ->
                    lotteryInfoEntity.descString = if (lotteryInfoEntity.amountType == 1) {
                        "${(lotteryInfoEntity.amount ?: "0").toDouble().finialDouble()}金币"
                    } else {
                        "${(lotteryInfoEntity.amount ?: "0").toDouble().finialDouble()}天"
                    }
                }

                listLottery = it.data!!
                mPrizeAdapter.setItems(listLottery)

            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }


    }


    /**
     * 适配器
     */
    private class SlotMachineAdapter(var mContext: Context) : AbstractWheelAdapter() {
        override fun getItemsCount(): Int {
            return 9
        }

        override fun getItem(index: Int, cachedView: View?, parent: ViewGroup): View {
            val view: View
            view =
                cachedView ?: View.inflate(mContext, R.layout.item_dialog_tiger_img, null)
            val img = view.findViewById<View>(R.id.iv_dialog_home_tiger) as ImageView
            when (index) {
//                0 -> img.setImageResource(R.mipmap.ic_roll1)
                0 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                1 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                2 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                3 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                4 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                5 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                6 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                7 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
                8 -> img.setImageResource(R.mipmap.icon_tigger_red_bag)
            }
            return view
        }
    }

    private fun showAdaVideo(type: Int) {
        showLoading("广告加载中...")
        //创建TTAdNative对象，createAdNative(Context context) context需要传入Activity对象
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(this)

        val adSlot = AdSlot.Builder()
            .setCodeId("956204408")
            .setOrientation(TTAdConstant.VERTICAL)
            .setAdLoadType(TTAdLoadType.LOAD)
            .build()

        mTTAdNative.loadRewardVideoAd(adSlot,
            object : TTAdNative.RewardVideoAdListener {
                override fun onError(p0: Int, p1: String?) {
                    LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1}")
                }

                override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                }

                override fun onRewardVideoCached() {
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?) {
                    dismissLoading()
                    ttRewardVideoAd!!.showRewardVideoAd(this@LotteryTiggerActivity)

                    ttRewardVideoAd.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            LogUtils.e(">>>> 广告展示")
                            // 广告展示
                        }

                        override fun onAdVideoBarClick() {
                            // 广告点击
                            LogUtils.e(">>>> 广告点击")
                        }

                        override fun onAdClose() {
                            // 广告关闭
                            LogUtils.e(">>>> 广告关闭")
                        }

                        override fun onVideoComplete() {
                            LogUtils.e(">>>> 广告素材播放完成，例如视频未跳过，完整的播放了")
                        }

                        override fun onVideoError() {
                            LogUtils.e(">>>> 广告展示时出错")
                        }

                        override fun onRewardVerify(
                            p0: Boolean,
                            p1: Int,
                            p2: String?,
                            p3: Int,
                            p4: String?
                        ) {
                        }

                        // 奖励发放
                        override fun onRewardArrived(
                            p0: Boolean,
                            p1: Int,
                            p2: Bundle?
                        ) {
                            toastOnUi("奖励已发放")

                            viewModel.adverReward("", type)

                            LogUtils.e(">>>> 奖励发放")
                            LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1} \n ")
                        }

                        // // 用户在观看时点击了跳过
                        override fun onSkippedVideo() {
                            LogUtils.e(">>>> 用户在观看时点击了跳过")
                        }

                    })
                }
            })
    }
}